/**
 * 双色球工具类库
 * @version 1.1.0
 */
import ObjectUtils from "@/utils/ObjectUtils";
import ssqconfig from "@/config/ssq-config";

const { split_index, middle_lines, prize_info } = ssqconfig;

/**
 * 统计对象转为数组
 * @param {Object} data 统计对象。示例：{"01":5, "05":2, ... "35":1}
 * @param {Boolean} withCount 返回值是否包含次数信息，默认 false
 * @param {Object} option 配置。示例：{op:'>', value:5}
 * @returns 返回开奖号码
 */
export const statObjectToArr = (data, withCount = false, option = null) => {
    if (option) {
        data = ObjectUtils.filterObjectValues(data, option.op, option.value);
    }

    let list = [];
    for (let n in data) {
        list.push(withCount ? `${n}/${data[n]}` : n);
    }
    return list;
}

/**
 * 和值信息
 */
const sumInfo = {
    front: middle_lines[0].reduce((a, b) => { return parseInt(a) + parseInt(b) }),
    back: middle_lines[1].reduce((a, b) => { return parseInt(a) + parseInt(b) }),
    all: 0
}
sumInfo.all = sumInfo.front + sumInfo.back;

export { sumInfo };

/**
 * 计算中奖结果并着色
 * @param {String} drawResult 开奖号码
 * @param {Array} orderArr 订单列表
 * @param {Boolean} isSkip 是否过滤未中奖的记录
 * @returns {Array} 返回着色后的号码、状态、奖金、中奖数量、和值、和差
 */
export const calcOrder = (drawResult, orderList, isSkip = false) => {
    orderList = orderList ? orderList.filter(item => item.trim().length > 0) : [];
    if (orderList.length == 0 || drawResult.trim().length == 0) {
        return orderList.map(order => {
            return {
                order,
                text: order,
                frontCount: 0,
                backCount: 0,
                totalCount: 0,
                statusText: '-',
                status: 0,
                moneyText: '-',
                money: 0,
                sum: 0,
                diffSum: 0,
            }
        });
    }
    let arrTemp = [], resultArr = [], orderArr = [], list = [];
    let rowArr = [];
    let frontCount = 0, backCount = 0, statusText = '', status = 0, money = 0, moneyText = '', sum = 0, diffSum = 0;
    arrTemp = drawResult.trim().split(' ');
    resultArr = [
        arrTemp.slice(0, split_index),
        arrTemp.slice(split_index)
    ];

    for (let order of orderList) {
        order = order.trim();
        arrTemp = order.split(' ');
        orderArr = [
            arrTemp.slice(0, split_index),
            arrTemp.slice(split_index)
        ];
        sum = arrTemp.reduce((a, b) => { return parseInt(a) + parseInt(b) });
        diffSum = sum - sumInfo.all;
        rowArr = [];
        frontCount = 0;
        backCount = 0;
        statusText = '未中奖';
        status = 10;
        moneyText = 0;
        money = 0;
        orderArr[0].forEach(str => {
            if (resultArr[0].includes(str)) {
                rowArr.push(`<strong class="text-red-400">${str}</strong>`);
                frontCount++;
            } else {
                rowArr.push(str);
            }
        })
        orderArr[1].forEach(str => {
            if (resultArr[1].includes(str)) {
                rowArr.push(`<strong class="text-red-400">${str}</strong>`);
                backCount++;
            } else {
                rowArr.push(str);
            }
        })
        if (frontCount > 0 || backCount > 0) {
            for (let prizeItem of prize_info) {
                if (prizeItem.front == frontCount && prizeItem.back == backCount) {
                    statusText = prizeItem.text;
                    status = prizeItem.value;
                    moneyText = prizeItem.moneyText;
                    money = prizeItem.money;
                }
            }
        }
        if (isSkip && money == 0) {
            continue;
        }
        list.push({
            order,
            text: rowArr.join(' '),
            frontCount,
            backCount,
            totalCount: frontCount + backCount,
            statusText,
            status,
            moneyText,
            money,
            sum,
            diffSum,
        })
    }
    console.log('list', list)
    return list;
}

/**
 * 计算购物车中奖号码并着色
 * @param {String} drawResult 
 * @param {Object} cartData 
 * @returns {Array}
 */
export const calcCart = (drawResult, cartData) => {
    if (Object.keys(cartData).length == 0 || drawResult.trim().length == 0) {
        return [];
    }

    let arrTemp = [], resultArrFront = [], resultArrBack = [], list = [], rowArr = [], count = 0;
    arrTemp = drawResult.trim().split(' ');
    resultArrFront = arrTemp.slice(0, split_index);
    resultArrBack = arrTemp.slice(split_index);

    let i = 0, num = '';
    for (let n in cartData) {
        i = parseInt(n) - 1;
        arrTemp = cartData[n].trim().split(' ');
        rowArr = [];
        if (i < split_index) {
            num = resultArrFront[i];
            arrTemp.forEach(str => {
                if (str == num) {
                    rowArr.push(`<strong class="text-red-400">${str}</strong>`);
                    count++;
                } else {
                    rowArr.push(str);
                }
            })
        } else {
            num = resultArrBack[i - split_index];
            arrTemp.forEach(str => {
                if (str == num) {
                    rowArr.push(`<strong class="text-red-400">${str}</strong>`);
                    count++;
                } else {
                    rowArr.push(str);
                }
            })
        }
        list.push({
            text: rowArr.join(' '),
            count,
        })
    }
    return list;
}


/**
 * 合并购物车并计算购物车中奖号码并着色
 * @param {String} drawResult 
 * @param {Array} cartArr 
 * @returns {Array}
 */
export const calcCartForMerge = (drawResult, cartArr, isAll = false) => {
    if (cartArr.length == 0 || cartArr[0].length == 0) {
        if (isAll) {
            return {
                text: '',
                count: 0,
                drawalCount: 0
            };
        }
        return {
            frontText: '',
            backText: '',
            frontCount: 0,
            backCount: 0,
            count: 0,
            frontDrawalCount: 0,
            backDrawalCount: 0,
            drawalCount: 0
        };
    }
    if (!drawResult) {
        drawResult = '00 00 00 00 00 00 00';
    }
    let arrTemp = [], resultArrFront = [], resultArrBack = [], drawalCount = 0, rowArr = [];
    arrTemp = drawResult.trim().split(' ');
    resultArrFront = arrTemp.slice(0, split_index);
    resultArrBack = arrTemp.slice(split_index);

    if (isAll) {
        let zoneAll = [];
        for (let arrRow of cartArr) {
            zoneAll = zoneAll.concat(arrRow);
        }
        zoneAll = [...new Set(zoneAll)].sort();
        zoneAll.forEach(str => {
            if (arrTemp.includes(str)) {
                rowArr.push(`<strong class="text-red-400">${str}</strong>`);
                drawalCount++;
            } else {
                rowArr.push(str);
            }
        })
        return {
            text: rowArr.join(' '),
            count: rowArr.length,
            drawalCount
        };
    }

    let zoneFront = [], zoneBack = [], lineArrBack = [], backDrawalCount = 0;
    cartArr.forEach((arrRow, i) => {
        if (i < split_index) {
            zoneFront = zoneFront.concat(arrRow);
        } else {
            zoneBack = zoneBack.concat(arrRow);
        }
    })
    zoneFront = [...new Set(zoneFront)].sort();
    zoneBack = [...new Set(zoneBack)].sort();
    zoneFront.forEach(str => {
        if (resultArrFront.includes(str)) {
            rowArr.push(`<strong class="text-red-400">${str}</strong>`);
            drawalCount++;
        } else {
            rowArr.push(str);
        }
    })
    zoneBack.forEach(str => {
        if (resultArrBack.includes(str)) {
            lineArrBack.push(`<strong class="text-red-400">${str}</strong>`);
            backDrawalCount++;
        } else {
            lineArrBack.push(str);
        }
    })

    return {
        frontText: rowArr.join(' '),
        backText: lineArrBack.join(' '),
        frontCount: rowArr.length,
        backCount: lineArrBack.length,
        count: rowArr.length + lineArrBack.length,
        frontDrawalCount: drawalCount,
        backDrawalCount,
        drawalCount: drawalCount + backDrawalCount
    };
}

/**
 * 号码着色
 * @param {String} drawResult 开奖号码
 * @param {String} text 预选号码
 * @param {String} type 类型。F:前区, B:后区, A:全部
 * @returns 
 */
export const colorResultText = (drawResult, text, type) => {
    let data = {
        text: '',
        count: 0,
        drawalCount: 0
    }
    if (drawResult.trim().length == 0 || !text) {
        return data;
    }
    text = text.trim().replace(/\s+/g, ' ');
    drawResult = drawResult.trim().replace(/\s+/g, ' ');
    let arrTemp = [], resultArrFront = [], resultArrBack = [], rowArr = [];
    arrTemp = drawResult.split(' ');
    resultArrFront = arrTemp.slice(0, split_index);
    resultArrBack = arrTemp.slice(split_index);
    if (type == 'A') {
        let textArr = text.split(', ');
        data.count = textArr[0].split(' ').length;
        resultArrFront.forEach(v => {
            textArr[0] = textArr[0].replaceAll(v, `<strong class="text-red-400">${v}</strong>`);
            data.drawalCount += (textArr[0].match(new RegExp(v, 'g')))?.length || 0;
        })
        if (textArr.length > 1) {
            data.count += textArr[1].split(' ').length;
            resultArrBack.forEach(v => {
                textArr[1] = textArr[1].replaceAll(v, `<strong class="text-red-400">${v}</strong>`);
                data.drawalCount += (textArr[1].match(new RegExp(v, 'g')))?.length || 0;
            })
        }
        data.text = textArr.join(', ');
        return data;
    }
    if (type == 'F') {
        data.count = text.split(' ').length;
        resultArrFront.forEach(v => {
            text = text.replaceAll(v, `<strong class="text-red-400">${v}</strong>`);
            data.drawalCount += (text.match(new RegExp(v, 'g')))?.length || 0;
        })
        data.text = text;
        return data;
    }
    if (type == 'B') {
        data.count = text.split(' ').length;
        resultArrBack.forEach(v => {
            text = text.replaceAll(v, `<strong class="text-red-400">${v}</strong>`);
            data.drawalCount += (text.match(new RegExp(v, 'g')))?.length || 0;
        })
        data.text = text;
        return data;
    }
    data.count = text.split(' ').length;
    text.split(' ').forEach((str, i) => {
        if ((resultArrFront.includes(str) && i < 6 && 'F' == type)
            || (resultArrBack.includes(str) && i >= 6 && 'B' == type)
            || (arrTemp.includes(str) && 'A' == type)
        ) {
            rowArr.push(`<strong class="text-red-400">${str}</strong>`);
            data.drawalCount++;
        } else {
            rowArr.push(str);
        }
    })
    data.text = rowArr.join(' ');
    return data;
}

/**
 * 二维数组排列组合
 * @param {Array} dimensionalArr 
 * @returns 
 */
export const combination = (dimensionalArr) => {
    const length = dimensionalArr.length;
    if (length >= 2) {
        const length1 = dimensionalArr[0].length;
        const length2 = dimensionalArr[1].length;
        const lengthProd = length1 * length2;
        const temporary = new Array(lengthProd);
        let index = 0;
        for (let i = 0; i < length1; i++) {
            for (let j = 0; j < length2; j++) {
                if (Array.isArray(dimensionalArr[0][i])) {
                    temporary[index] = [].concat([...dimensionalArr[0][i], dimensionalArr[1][j]]);
                } else {
                    temporary[index] = [].concat([dimensionalArr[0][i], dimensionalArr[1][j]]);
                }
                index++;
            }
        }
        const newArray = new Array(length - 1);
        newArray[0] = temporary;
        for (let j = 2; j < length; j++) {
            newArray[j - 1] = dimensionalArr[j];
        }
        return combination(newArray);
    } else {
        if (dimensionalArr[0] && dimensionalArr[0][0] && Array.isArray(dimensionalArr[0][0])) {
            return dimensionalArr[0];
        }
        return dimensionalArr;
    }
}

/**
 * 二维数组排列组合，只保留中奖的组合
 * @param {Array} dimensionalArr 
 * @returns 
 */
export const combinationForDrawal = (result, dimensionalArr) => {
    let data = {
        rowsCount: 0,
        drawalCount: 0,
        bonus: 0,
        bestPrize: '',
        statusValueMin: 10,
        list: [],
    };
    let orderItem = null;
    function combinationFn(dimensionalArr) {
        const length = dimensionalArr.length;
        if (length >= 2) {
            const length1 = dimensionalArr[0].length;
            const length2 = dimensionalArr[1].length;
            const lengthProd = length1 * length2;
            const temporary = new Array(lengthProd);
            let index = 0;
            for (let i = 0; i < length1; i++) {
                for (let j = 0; j < length2; j++) {
                    if (Array.isArray(dimensionalArr[0][i])) {
                        temporary[index] = [].concat([...dimensionalArr[0][i], dimensionalArr[1][j]]);
                        if (temporary[index].length == 7) {
                            orderItem = calcOrder(result, [temporary[index].join(' ')])[0];
                            if (data.statusValueMin < orderItem.status) {
                                data.statusValueMin = orderItem.status;
                                data.bestPrize = orderItem.status;
                            }
                            if (orderItem.money > 0) {
                                data.bonus += orderItem.money;
                                data.drawalCount++;
                                data.list.push(orderItem);
                            }
                            data.rowsCount++;
                        }
                    } else {
                        temporary[index] = [].concat([dimensionalArr[0][i], dimensionalArr[1][j]]);
                    }
                    index++;
                }
            }
            const newArray = new Array(length - 1);
            newArray[0] = temporary;
            for (let j = 2; j < length; j++) {
                newArray[j - 1] = dimensionalArr[j];
            }
            return combinationFn(newArray);
        } else {
            if (dimensionalArr[0] && dimensionalArr[0][0] && Array.isArray(dimensionalArr[0][0])) {
                return dimensionalArr[0];
            }
            return dimensionalArr;
        }
    }
    combinationFn(dimensionalArr);
    return data;
}

/**
 * 解析 AI 推荐选号
 * @param {String} text AI 选号内容
 * @param {String} provider AI 服务提供商
 * @returns {Array} 返回号码数组
 */
export const parseAiText = (text, provider) => {
    let matches = null;
    switch (provider) {
        case 'nami':
            // 解析纳米搜索内容
            // 【示例】
            // 前区 05, 14, 20, 29, 33 | 后区 04, 10
            // 前区：12 15 19 26 31 | 后区：05 12
            // 前区：09, 14, 21, 27, 34
            // 后区：05, 10
            // 逻辑：热号主导（14、20、29近10期高频）+ 冷号回补（05遗漏≥8期），后区1路偶数组合（04、10）5。
            matches = text.match(/前区：?\s?(\d{2}(\,?\s?\d{2}){5})\s*\|?\s*后区：?\s?(\d{2}(\,?\s?\d){1})/ig);
            if (matches) {
                // ['前区 05, 14, 20, 29, 33 | 后区 04, 10', '前区 13, 17, 23, 30, 34 | 后区 02, 08', ...]
                return matches.map(v => v.replace(/前区：?\s?|后区：?\s?|\||\,/g, ' ').replace(/\s{2,}/g, ' ').trim());
            }
            //【示例】
            // 1	05,14,20,29,33	04,10	冷热搭配（05冷+33热），后区1路偶数组合6。
            // 2	13,17,23,30,34	02,08	热号（23、30）+冷号回补（13、17）6。
            // 10	09,15,20,27,31	02,11	高频冷热组合（09冷+20热）23。
            matches = text.match(/(\d{2}(,*\s*\d{2}){5})\s*[\+\|]*\s*(\d{2}(,*\s*\d{1}))/ig);
            if (matches) {
                // ['前区 05, 14, 20, 29, 33 | 后区 04, 10', '前区 13, 17, 23, 30, 34 | 后区 02, 08', ...]
                return matches.map(v => v.replace(/\,/g, ' ').replace(/\s+/gi, ' ').trim());
            }
            break;
        case 'deepseek':
            // 解析 DeepSeek 内容
            // 【示例】
            // 第1注：03 11 18 24 32 + 05 09
            // 第2注：07 14 19 27 33 + 02 08
            matches = text.match(/(\d{2}(,*\s*\d{2}){5})\s*\+\s*(\d{2}(,*\s*\d{1}))/ig);
            if (matches) {
                // ['前区 05, 14, 20, 29, 33 | 后区 04, 10', '前区 13, 17, 23, 30, 34 | 后区 02, 08', ...]
                return matches.map(v => v.replace(/\+/g, '').replace(/\s{2,}/g, ' ').trim());
            }
            break;
    }
    return [];
}

/**
 * 解析订单号码到综合选号池（前区和后区）
 * @param {Array} list 订单号码列表
 * @param {Boolean} isPlane 是否把数组合并为字符串
 * @returns {Object} {frontData: [], backData: []}
 */
export const ordersToPoolAll = (list, isPlane = true) => {
    if (!list || list.length === 0) {
        return { frontData: [], backData: [] };
    }
    let frontData = [], backData = [], item = [];
    list.forEach(line => {
        item = line.replace('/\s{2}/', ' ').split(' ').filter(v => v.trim().length == 2);
        if (item.length == 7) {
            frontData = frontData.concat(item.slice(0, split_index));
            backData = backData.concat(item.slice(split_index));
        }
    })
    const data = {
        frontData: Array.from(new Set(frontData)).sort(),
        backData: Array.from(new Set(backData)).sort()
    };
    return isPlane ? `${data.frontData.join(' ')}, ${data.backData.join(' ')}` : data;
}

/**
 * 解析订单号码到 7 个号数选号池
 * @param {Array} list 
 * @returns {Array} [[],[],[],[],[],[],[]]
 */
export const ordersToPoolColumns = (list) => {
    if (!list || list.length === 0) {
        return [];
    }
    let item = [], data = [[], [], [], [], [], [], []];
    list.forEach(line => {
        item = line.replace('/\s{2}/', ' ').split(' ').filter(v => v.trim().length == 2);
        if (item.length == 7) {
            for (let i in item) {
                if (!data[i].includes(item[i])) {
                    data[i].push(item[i]);
                }
            }
        }
    })
    for (let i = 0; i < data.length; i++) {
        data[i] = Array.from(new Set(data[i])).sort();
    }
    return data;
}